#pragma once

#include <iostream>
#include <queue>
#include <pthread.h>
#include "LockGuard.hpp"

const int default_capacity = 5;

template<class T>
class BlockQueue
{
public:
    BlockQueue(int capacity = default_capacity)
    : _capacity(capacity)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
    }

    void put(const T& task)
    {
        {
            LockGuard lockGuard(&_mutex);
            while(isFull() == true)
            {
                pthread_cond_wait(&_p_cond, &_mutex);
            }
            _q.push(task);
            pthread_cond_signal(&_c_cond);
        }
    }

    void take(T* task)
    {
        {
            LockGuard lockGuard(&_mutex);
            while(isEmpty() == true)
            {
                pthread_cond_wait(&_c_cond, &_mutex);
            }
            *task = _q.front();
            _q.pop();
            pthread_cond_signal(&_p_cond);
        }
    }

    bool isFull()
    {
        return _q.size() == _capacity;
    }

    bool isEmpty()
    {
        return _q.size() == 0;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_p_cond);
        pthread_cond_destroy(&_c_cond);
    }
private:
    std::queue<T> _q;
    int _capacity;
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond;
    pthread_cond_t _c_cond;
};